/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.apt.DBprocess;

import com.apt.createAdmin.NewAccAdminForm;
import com.apt.tag.Connect_DB;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author Bach
 */
public class InsertAccAdmin {

    public static boolean insert_NewAcc(NewAccAdminForm admin) {
        boolean re = false;
        Connection cnn = Connect_DB.getConnection();
        PreparedStatement ps = null;
        String qurey = "INSERT INTO [Matrimony].[dbo].[Accounts] "
                + "           ([User_Password],[User_Name],[User_Email],[Account_Status],[Account_Role],[Date_Registed],[Date_Expired])"
                + "            VALUES  (?,?,?,?,?,?,?)";
        try {

            if (cnn != null) {
                String usname = admin.getUsername();
                String usemail = admin.getEmail();
                String uspass = admin.getPass();
                //kiem tra su ton tai
                if (checkexits(usemail, usname, cnn)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                    Date d = new Date(System.currentTimeMillis());

                    ps = cnn.prepareStatement(qurey);
                    ps.setString(1, uspass);
                    ps.setString(2, usname);
                    ps.setString(3, usemail);
                    ps.setByte(4, new Byte("1"));
                    ps.setString(5, "admin");
                    ps.setDate(6, new java.sql.Date(d.getTime()));
                    ps.setDate(7, null);
                    int i = ps.executeUpdate();
                    if (i > 0) {
                        return true;
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Connect_DB.close(null, null, ps, cnn);
        }
        return re;
    }

    private static boolean checkexits(String email, String usname, Connection cnn) {
        boolean re = false;
        PreparedStatement ps;
        String sql = " SELECT [User_Name],[User_Email]"
                + "  FROM [Matrimony].[dbo].[Accounts]"
                + "  where User_Name=? and User_Email=? ";
        ResultSet rs = null;
        try {
            ps = cnn.prepareStatement(sql);
            ps.setString(1, usname);
            ps.setString(2, email);
            rs = ps.executeQuery();
            if (rs.next()) {
                return false;
            }else{
                return true; 
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return re;
    }
}
